<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <!--      <el-form-item label="账户名" prop="userName">-->
      <!--        <el-input-->
      <!--            v-model="queryParams.userName"-->
      <!--            placeholder="请输入账户名"-->
      <!--            clearable-->
      <!--            @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="设备mac" prop="deviceMac">
        <el-input
          v-model="queryParams.deviceMac"
          placeholder="请输入设备mac"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="应用名称" prop="appName">
        <el-input
          v-model="queryParams.appName"
          placeholder="请输入应用名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="有效期" prop="validity">
        <el-input
          v-model="queryParams.validity"
          placeholder="请输入有效期"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['deviceBox:appAccount:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['deviceBox:appAccount:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['deviceBox:appAccount:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['deviceBox:appAccount:export']"
          >导出</el-button
        >
       
      </el-col>
      <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['system:user:import']"
            >导入</el-button
          >
        </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="appAccountList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="账户名"
        align="center"
        prop="userName"
        v-if="columns[0].visible"
      />
      <el-table-column
        label="密码"
        align="center"
        prop="password"
        v-if="columns[1].visible"
      />
      <el-table-column
        label="激活码"
        align="center"
        prop="activateCode"
        v-if="columns[2].visible"
      />
      <el-table-column
        label="设备mac"
        align="center"
        prop="deviceMac"
        v-if="columns[3].visible"
      />
      <el-table-column
        label="应用名称"
        align="center"
        prop="appName"
        v-if="columns[4].visible"
      />
      <el-table-column
        label="类型"
        align="center"
        prop="type"
        v-if="columns[5].visible"
      />
      <el-table-column
        label="绑定状态"
        align="center"
        prop="bindStatus"
        v-if="columns[6].visible"
      />
      <el-table-column
        label="有效期"
        align="center"
        prop="validity"
        v-if="columns[7].visible"
      />
      <el-table-column
        label="备注"
        align="center"
        prop="remark"
        v-if="columns[8].visible"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['deviceBox:appAccount:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['deviceBox:appAccount:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改应用激活码管理对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      :width="dialogWidth"
      append-to-body
    >
      <el-form ref="appAccountRef" :model="form" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="账户名" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入账户名" />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入密码" />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="激活码" prop="activateCode">
              <el-input
                v-model="form.activateCode"
                placeholder="请输入激活码"
              />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="设备mac" prop="deviceMac">
              <el-input v-model="form.deviceMac" placeholder="请输入设备mac" />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="应用" prop="devicAppId">
              <el-select
                v-model="form.devicAppId"
                placeholder="请选择应用"
                filterable
                clearable
              >
                <el-option
                  v-for="item in appIdOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="有效期" prop="validity">
              <el-input v-model="form.validity" placeholder="请输入有效期" />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入激活码对话框 -->
    <el-dialog
      title="导入激活码"
      v-model="importDialogVisible"
      width="400px"
      append-to-body
    >
      <el-form>
        <el-form-item label="应用">
          <el-select v-model="importAppId" placeholder="请选择应用" filterable>
            <el-option
              v-for="item in appIdOptions"
              :key="item.id"
              :label="item.columnName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="上传文件" prop="file">
          <el-upload
            ref="uploadRef"
            action="#"
            :limit="1"
            accept=".xls,.xlsx"
            :auto-upload="false"
            :on-change="handleChange"
            :on-remove="handleRemove"
          >
            <template #trigger>
              <el-button type="primary">上传文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">只支持xls或xlsx格式文件.</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="submitImport">导入</el-button>
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="info" @click="downloadTemplate">下载模板</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="AppAccount">
import {
  listAppAccount,
  getAppAccount,
  delAppAccount,
  addAppAccount,
  updateAppAccount,
  importAppAccount
} from "@/api/deviceBox/appAccount";
import { getAppInfoByColumnId } from "@/api/deviceBox/column";

const { proxy } = getCurrentInstance();

const appAccountList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 列显隐信息
const columns = ref([
  { key: 0, label: `账户名`, visible: true },
  { key: 1, label: `密码`, visible: true },
  { key: 2, label: `激活码`, visible: true },
  { key: 3, label: `设备id`, visible: true },
  { key: 4, label: `appid`, visible: true },
  { key: 5, label: `类型`, visible: true },
  { key: 6, label: `绑定状态：0未绑定，1已绑定`, visible: true },
  { key: 7, label: `有效期`, visible: true },
  { key: 8, label: `备注`, visible: true },
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: null,
    password: null,
    activateCode: null,
    deviceMac: null,
    devicAppId: null,
    type: null,
    bindStatus: null,
    validity: null,
  },
  // rules: {
  //   userName: [
  //     { required: true, message: "账户名不能为空", trigger: "blur" }
  //   ],
  //   password: [
  //     { required: true, message: "密码不能为空", trigger: "blur" }
  //   ],
  // }
});

const { queryParams, form, rules } = toRefs(data);

const appIdOptions = ref([]);

// 导入相关
const importDialogVisible = ref(false);
const importAppId = ref(null);
const importFile = ref(null);
const uploadRef = ref(null);


const handleChange = (file) => {
  importFile.value = file.raw;
};
const handleRemove = (file) => {
  importFile.value = null;
};


function handleImport() {
  importDialogVisible.value = true;
  importAppId.value = null;
  importFile.value = null;
  nextTick(() => {
    if (uploadRef.value) {
      uploadRef.value.clearFiles();
    }
  });
}

function submitImport() {
  if (!importAppId.value) {
    proxy.$modal.msgError("请选择应用");
    return;
  }
  if (!importFile.value) {
    proxy.$modal.msgError("请上传文件");
    return;
  }
  const formData = new FormData();
  formData.append("appId", importAppId.value);
  formData.append("file", importFile.value);
  loading.value = true;
  importAppAccount(formData)
    .then((res) => {
      proxy.$modal.msgSuccess("导入成功");
      importDialogVisible.value = false;
      getList();
    })
    .catch(() => {
      proxy.$modal.msgError("导入失败");
    })
    .finally(() => {
      loading.value = false;
    });
}

function downloadTemplate() {
  window.open(
    "https://www.huadunyun.cn/files/template/activateCodeTemplate.xlsx"
  );
}

/** 查询应用激活码管理列表 */
function getList() {
  loading.value = true;
  listAppAccount(queryParams.value).then((response) => {
    appAccountList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userName: null,
    password: null,
    activateCode: null,
    deviceMac: null,
    devicAppId: null,
    type: null,
    bindStatus: null,
    validity: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
  };
  proxy.resetForm("appAccountRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加应用激活码管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getAppAccount(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改应用激活码管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["appAccountRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateAppAccount(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addAppAccount(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除应用激活码管理编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delAppAccount(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "deviceBox/appAccount/export",
    {
      ...queryParams.value,
    },
    `appAccount_${new Date().getTime()}.xlsx`
  );
}

getList();

/** 动态计算字段数 **/
const fieldCount = ref(0);

onMounted(() => {
  // 统计表单字段数量
  fieldCount.value = [
    "userName",
    "password",
    "activateCode",
    "deviceMac",
    "devicAppId",
    "type",
    "bindStatus",
    "validity",
    "remark",
  ].length;

  // 获取 appid 下拉数据
  getAppInfoByColumnId().then((res) => {
    appIdOptions.value = res.rows || [];
  });
});

const isTwoColumnForm = computed(() => fieldCount.value > 8);
const dialogWidth = computed(() => (isTwoColumnForm.value ? "60vw" : "500px"));
</script>
